const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const path = require('path');
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const jwt = require('koa-jwt');
const cors = require('koa2-cors')

// 处理文件上传的插件
const koaBody = require('koa-body')

const { SussessModel, FailModel } = require('./extend/helper')

const index = require('./routes/index')
const users = require('./routes/users')

app.helper = {SussessModel, FailModel};

// 检测 是否 携带token;
// app.use(jwt({ secret: SECRET }).unless({
//   // 登录接口不需要验证
//   path: [
//     /^\/v1\/login/,
//     /^\/v1\/register/,
//     /^\/v1\/addMenu/,
//    /^\/api\/test/,
//    /^\/api\/login/,
//   ]
// }));

// error handler
onerror(app)

app.use(koaBody({
  multipart: true, // 支持文件上传
  formidable: { // 解析 放置
    uploadDir: path.join(__dirname, '/public/uploads'), // 放置图片区域
    keepExtensions: true, // 保持图片后缀名字
  },
}));

// middlewares
app.use(bodyparser({
  enableTypes:['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

app.use(views(__dirname + '/views', {
  extension: 'pug'
}))

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

app.use(cors())
// routes
app.use(index.routes(), index.allowedMethods())
app.use(users.routes(), users.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app
